﻿using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEditor;
using System.Linq;
using System.Text;

public class AddressableResFile
{
    public string   address;
    public string   addressHash;
    public string   addressPath;
    public string[] addressLabel;
}


public class AddressableResGroup
{
    string rootRes;
    string rootAssets;

    public string name = "Main";
    public List<AddressableResFile> resFiles;

    AddressableCustomGroup customGroup;

    public AddressableResGroup(DirectoryInfo group)
    {
        resFiles   = new List<AddressableResFile>();
        rootRes    = $"{Application.dataPath}/{AddressableBuildTools.addressAssets}/";
        rootAssets = $"{Environment.CurrentDirectory.Replace('\\', '/')}/";

        customGroup = AddressableCustomGroupMgr.SetCustomGroupPath(group.FullName);

        GroupFindLabels(group);

        AssetDatabase.SaveAssets();
    }

    void GroupFindLabels(DirectoryInfo dirName)
    {
        //搜集当前组 Label 的 物体
        var dirs = dirName.GetDirectories();
        foreach (var item in dirs)
        {
            var label = item.Name.Replace(AddressableBuildTools.LabelTag, "");
            var labelTags = label.Split('_');

            LabelFindFiles(new DirectoryInfo(item.FullName), label, labelTags);
        }

        //搜集当前组没有label的物体
        LabelFiles(dirName.GetFiles(), "default", new string[] { });

        RemoveSurplus(dirs);
    }

    void RemoveSurplus(DirectoryInfo[] dirs)
    {
        List<string> filters = new List<string>() { "default" };
        List<AddressableCustomGroup.LabelInfo> needInfos = new List<AddressableCustomGroup.LabelInfo>();

        foreach (var item in dirs)
        {
            filters.Add(item.Name.Replace(AddressableBuildTools.LabelTag,""));
        }


        foreach (var item in customGroup.labels)
        {
            if (filters.Contains(item.labelName))
            {
                continue;
            }
            needInfos.Add(item);
        }

        foreach (var item in needInfos)
        {
            customGroup.labels.Remove(item);
        }
    }

    void LabelFindFiles(DirectoryInfo dirName,string label, string[] labels)
    {
        LabelFiles(dirName.GetFiles(), label,labels);

        if (dirName.GetDirectories().Length > 0)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("格式不对，文件夹层数过多 => 标准 Local");
            builder.AppendLine("                               L (Group)x");
            builder.AppendLine("                                   L (Label)y ");
            Debug.LogError(builder.ToString());
        }
    }

    private void LabelFiles(FileInfo[] files, string label, string[] labels)
    {
        if (files.Length <= 0)
            return;

        var labelInfo = customGroup.labels
            .Where((_) =>
                {
                    if (_ == null) return false;
                    return _.labelName == label;
                })
            .FirstOrDefault();
        if( labelInfo == null)
        {
            labelInfo = new AddressableCustomGroup.LabelInfo()
            {
                labelName = label,
                entryInfos = new List<AddressableCustomGroup.EntryInfo>()
            };
            customGroup.labels.Add(labelInfo);
        }
        labelInfo.entryInfos.Clear();



        foreach (var file in files)
        {
            if (file.Name.Contains(".meta")|| file.Name.Contains("CustomGroup.asset"))
                continue;

            var subKey = file.FullName
                .Replace('\\', '/')
                .Replace(rootRes, "")
                .Replace(AddressableBuildTools.GroupTag, "")
                .Replace(AddressableBuildTools.LabelTag, "");


            var subValue = file.FullName
                .Replace('\\', '/')
                .Replace(rootAssets, "");


            AddressableResFile resFile      = new AddressableResFile();
            resFile.address      = IsSamepleName(labelInfo.isSampleName,subKey);
            resFile.addressPath  = subValue;
            resFile.addressLabel = labels;
            resFile.addressHash  = AssetDatabase.AssetPathToGUID(subValue);
            resFiles.Add(resFile);


            labelInfo.entryInfos.Add(new AddressableCustomGroup.EntryInfo()
            {
               address=  resFile.address, 
               addressPath= resFile.addressPath
            });
        }
    }

    public string IsSamepleName(bool isSample, string key)
    {
        if (!isSample)
        {
            return key.Remove(key.LastIndexOf('.'));
        }
        else
        {
            int lastID = key.LastIndexOf('/');
            if (lastID > 0)
            {
                key = key.Substring(lastID + 1, key.Length - lastID -1);
            }

            int remoID = key.LastIndexOf('.');
            if (remoID > 0)
            {
                key= key.Remove(remoID);
            }

            return key;
        }
    }
}

public class ResFolder 
{
    public string group;
    public List<AddressableResGroup> resGroups = new List<AddressableResGroup>();

    public ResFolder(DirectoryInfo group)
    {
        this.group = group.Name;
        var direcs = group.GetDirectories();
        var groups = direcs.Where((_) => _.Name.Contains(AddressableBuildTools.GroupTag));

        foreach (var item in groups)
        {
            resGroups.Add(new AddressableResGroup(item)
            {
                name = $"{this.group}_{item.Name}".Replace(AddressableBuildTools.GroupTag, "")
            });
        }
    }
}
